import requests
import sys
import time
import base64

def check_repo_branch(repo_name, headers):
    try:
        # Gerrit API 基础 URL
        base_url = "http://gerrit.gxatek.com:18080"
        
        # 检查仓库是否存在
        repo_url = f"{base_url}/a/projects/{repo_name}"
        response = requests.get(repo_url, headers=headers)
        
        if response.status_code == 404:
            print(f"错误: 仓库 {repo_name} 不存在")
            return False
        elif response.status_code != 200:
            print(f"错误: 查询仓库 {repo_name} 时发生错误，状态码: {response.status_code}")
            return False

        # 检查特定分支是否存在
        branch_url = f"{base_url}/a/projects/{repo_name}/branches/8155_T09G_S.0"
        response = requests.get(branch_url, headers=headers)
        
        if response.status_code == 200:
            # print(f"仓库 {repo_name} 存在分支 8155_T09G_S.0")
            return True
        elif response.status_code == 404:
            repo_name = repo_name.replace("%2F", "/")
            print(f"仓库 {repo_name} 不存在分支 8155_T09G_S.0")
            return False
        else:
            print(f"错误: 查询分支时发生错误，状态码: {response.status_code}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"检查仓库 {repo_name} 时发生网络错误: {str(e)}")
        return False
    except Exception as e:
        print(f"检查仓库 {repo_name} 时发生错误: {str(e)}")
        return False

def main():
    try:
        username = "gerrit_ibuild"
        password = "JvKpdszzBgq6Ppj5sfkhDx++Am6yNWFYHQPzR7+eLQ"
        
        # 创建 Basic 认证的 Authorization header
        auth_str = f"{username}:{password}"
        auth_bytes = auth_str.encode('ascii')
        base64_auth = base64.b64encode(auth_bytes).decode('ascii')
        
        headers = {
            "Authorization": f"Basic {base64_auth}",
            "Content-Type": "application/json"
        }
        
        with open('repo.txt', 'r') as file:
            for line in file:
                line = line.strip()
                if line.startswith('name="'):
                    # 提取仓库名称
                    repo_name = line.split('name="')[1].rstrip('"')
                    # 将仓库名称中的 / 替换为 %2F
                    repo_name = repo_name.replace('/', '%2F')
                    check_repo_branch(repo_name, headers)
                    # 添加延迟以避免触发 API 速率限制
                    time.sleep(1)
    except FileNotFoundError:
        print("错误: 找不到 repo.txt 文件")
        sys.exit(1)
    except Exception as e:
        print(f"发生错误: {str(e)}")
        sys.exit(1)

if __name__ == "__main__":
    main() 